package com.sh.apibackend.utils;

import lombok.extern.slf4j.Slf4j;

/**
 * 令牌桶
 */
@Slf4j
public class LeakyBucket {
//    private long timeStamp = System.currentTimeMillis(); // 上一次水进桶的时间
    public final int tokenCapacity;  // 令牌桶容量
    public final int rate;   // 令牌生成速度
    public long nowTokens;  // 当前令牌数

    // Email 令牌桶
    public static LeakyBucket registerEmailLeakyBucket = new LeakyBucket(1,1);


    public LeakyBucket(int tokenCapacity, int rate) {
        this.tokenCapacity = tokenCapacity;
        this.rate = rate;
    }



    public boolean control(long lastTime){
        long nowTime = System.currentTimeMillis()/1000;   // 当前时间
        if ((nowTime-lastTime)>=60){
            nowTokens =  nowTokens + (long) rate;
        }
        long tokens = Math.min(tokenCapacity, nowTokens);  // 累积令牌数

        if (tokens>0){
            tokens--;
            //记录令牌桶剩余令牌数量
            nowTokens = tokens;
            log.info("剩余令牌桶数量："+nowTokens);
            return true;
        }else {
            return false;
        }
    }

}
